package com.example.pt.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Calendar;

public class JWTUtil {
    private static final String SECRET = "!DAR$";
    private static final Algorithm algorithm = Algorithm.HMAC256(SECRET);
    private static final Logger logger = LoggerFactory.getLogger(JWTUtil.class);

    public static String generateToken(int userType, int uid) {

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND, 60000);

        JWTCreator.Builder builder = JWT.create();
        builder.withClaim("usertype", userType);
        builder.withClaim("uid", uid);
        String token = builder.withExpiresAt(calendar.getTime()).sign(algorithm);
        System.out.println(token);
        return token;
    }

    public static DecodedJWT verifyToken(String token) throws TokenExpiredException {
        try {
            if (token == null || token.isEmpty()) {
                logger.warn("令牌为空，无法验证");
                System.out.println("令牌为空，无法验证");
                return null;
            }
            
            logger.debug("开始验证令牌: {}", token.substring(0, Math.min(token.length(), 20)) + "...");
            System.out.println("开始验证令牌: " + token.substring(0, Math.min(token.length(), 20)) + "...");
            
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT decodedJWT = verifier.verify(token);

            // 打印令牌内容用于调试
            try {
                int userType = decodedJWT.getClaim("usertype").asInt();
                int uid = decodedJWT.getClaim("uid").asInt();
                
                logger.info("令牌验证成功 - usertype: {}, uid: {}, 过期时间: {}", 
                        userType, uid, decodedJWT.getExpiresAt());
                System.out.println("令牌验证成功 - usertype: " + userType + 
                        ", uid: " + uid + ", 过期时间: " + decodedJWT.getExpiresAt());
            } catch (Exception e) {
                logger.warn("从令牌中提取信息时出错: {}", e.getMessage());
                System.out.println("从令牌中提取信息时出错: " + e.getMessage());
            }

            return decodedJWT;
        }
        catch(TokenExpiredException e) {
            logger.warn("令牌已过期: {}", e.getMessage());
            System.out.println("令牌已过期: " + e.getMessage());
            throw e;
        }
        catch(Exception e) {
            logger.error("令牌验证失败: {}", e.getMessage());
            System.out.println("令牌验证失败: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
}

